package cn.shiro.shiroservice.moudle.db.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.shiro.shiroservice.common.utils.FileUtils;
import cn.shiro.shiroservice.common.utils.SqlSessionUtils;
import cn.shiro.shiroservice.moudle.db.mapper.BackupMapper;
import cn.shiro.shiroservice.moudle.db.mapper.DataBaseMapper;
import cn.shiro.shiroservice.moudle.db.service.BaseBackUpService;
import com.alibaba.druid.pool.DruidDataSource;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * &#064;Time 2024 二月 星期六 13:32
 *
 * @author ShangGuan
 */
public class SimpleBaseBackUpServiceImpl implements BaseBackUpService {

    private final BackupMapper backupMapper;

    private final DataBaseMapper dataBaseMapper;

    /**
     * 备份表名称
     */
    @Getter
    @Setter
    private String backupTableName;
    /**
     * 默认路径
     */
    @Getter
    @Setter
    private String defaultPath;

    public SimpleBaseBackUpServiceImpl(BackupMapper backupMapper, DataBaseMapper dataBaseMapper, String backupTableName) {
        this.backupMapper = backupMapper;
        this.dataBaseMapper = dataBaseMapper;
        if (StrUtil.isBlank(backupTableName)) {
            throw new NullPointerException("backupTableName not is null and '' ");
        }
        this.backupTableName = backupTableName;
        String now = DateUtil.today();
        defaultPath = backupMapper.queryDatabaseInstallPath() + now + "/backup_data";
    }

    public SimpleBaseBackUpServiceImpl(BackupMapper backupMapper, DataBaseMapper dataBaseMapper, String backupTableName, String path) {
        this(backupMapper, dataBaseMapper, backupTableName);
        if (StrUtil.isNotBlank(path)) {
            defaultPath = path;
        }
    }

    @Override
    public void backup() {
        FileUtils.createPath(defaultPath);
        String tableSql = generationTableSql();
        String dataSql = generationInsertSql();
        FileUtils.write(tableSql, new File(defaultPath + backupTableName+".sql"));
        FileUtils.write(dataSql, new File(defaultPath + backupTableName+"_data.sql"));
    }

    @Override
    public String generationTableSql() throws NullPointerException {
        if (StrUtil.isBlank(backupTableName)) {
            throw new NullPointerException("backupTableName not is null and '' ");
        }
        Map<String, Object> generationTableSql = backupMapper.getGenerationTableSql(backupTableName);
        JSONObject jsonObject = JSONUtil.parseObj(generationTableSql.get(backupTableName));
        Object createTableSql = jsonObject.get("Create Table");

        return String.valueOf(createTableSql);
    }


    @Override
    public String generationInsertSql() {
        List<Map<String, Object>> maps = dataBaseMapper.selectTable(backupTableName);
        StringBuilder prefixSql = new StringBuilder("insert into " + backupTableName + "(");
        StringBuilder suffixSql = new StringBuilder(") values ");
        Iterator<Map<String, Object>> iterator = maps.iterator();
        if (CollectionUtils.isEmpty(maps)) {
            return null;
        }
        //生成values前面的数据
        while (iterator.hasNext()) {
            Map<String, Object> next = iterator.next();
            Iterator<Map.Entry<String, Object>> iterator2 = next.entrySet().iterator();
            while (iterator2.hasNext()) {
                String key = iterator2.next().getKey();
                prefixSql.append(key);
                if (iterator2.hasNext()) {
                    prefixSql.append(",");
                }
            }
            break;
        }
        //生成values 后面的值
        while (iterator.hasNext()) {
            Map<String, Object> next = iterator.next();
            suffixSql.append("(");
            Iterator<Map.Entry<String, Object>> iterator2 = next.entrySet().iterator();
            while (iterator2.hasNext()) {
                Object value = iterator2.next().getValue();
                suffixSql.append("'").append(value).append("'");
                if (iterator2.hasNext()) {
                    suffixSql.append(",");
                }
            }
            suffixSql.append(")");
            if (iterator.hasNext()) {
                suffixSql.append(",");
            }
        }
        return prefixSql.append(suffixSql).toString();
    }

    @Override
    public void importData() {

    }

    public static void main(String[] args) {
        // JDBC 连接信息
        String jdbcUrl = "jdbc:mysql://localhost:3306/db_backup_service?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
        String username = "root";
        String password = "12345678";
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(jdbcUrl);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        BackupMapper backupMapper = SqlSessionUtils.getSqlMapper(druidDataSource, BackupMapper.class);
        DataBaseMapper dataBaseMapper = SqlSessionUtils.getSqlMapper(druidDataSource, DataBaseMapper.class);
        String now = DateUtil.today();
        SimpleBaseBackUpServiceImpl backupService = new SimpleBaseBackUpServiceImpl(backupMapper, dataBaseMapper, "sys_role","/Users/apple/Desktop/cache/"+now+"/");
        backupService.backup();
    }
}
